package com.kongshidian.ui.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testpic.Bimp;
import com.example.testpic.FileUtils;
import com.kongshidian.App;
import com.kongshidian.Constants;
import com.kongshidian.R;
import com.kongshidian.ui.BaseActivity;
import com.kongshidian.ui.EvaluationActivity;
import com.kongshidian.ui.PhotoAlbumActivity;
import com.kongshidian.ui.PhotoPreviewActivity;
import com.kongshidian.ui.PublishedExportActivity;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 *  晒单  
 */
public class SingleFragment extends BaseFragment{
	private GridAdapter adapter;
	public static PublishedExportActivity instance = null;
	private GridView mGridView;
	private EditText mEditText;
	private Button mSureBut;
	private ImageView mProImg,isSunSingleImg;
	private TextView mProNameTxt,mProAttributeTxt,mProPriceTxt;
	private LinearLayout mLin;
	private RelativeLayout mButtomRelat;


	@Override  
	public View onCreateView(LayoutInflater inflater, ViewGroup container,  
			Bundle savedInstanceState) {  
		return inflater.inflate(R.layout.fragement_sunsingle, container, false);  
	}  

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mEditText  = (EditText) getView().findViewById(R.id.sunsingle_fragment_Edit);
		mProImg = (ImageView) getView().findViewById(R.id.sunsingle_fragment_product_image);
		isSunSingleImg = (ImageView) getView().findViewById(R.id.sunsingle_is_true_img);
		mProNameTxt = (TextView) getView().findViewById(R.id.sunsingle_fragment_product_name);
		mProAttributeTxt = (TextView) getView().findViewById(R.id.sunsingle_fragment_attribute);
		mProPriceTxt = (TextView) getView().findViewById(R.id.sunsingle_fragment_product_price);
		mLin = (LinearLayout) getView().findViewById(R.id.sunsingle_fragment_empty_relat);
		mButtomRelat = (RelativeLayout) getView().findViewById(R.id.sunsingle_fragment_buttom_relat);
		
		ImageLoader.getInstance().displayImage(EvaluationActivity.skuImage, mProImg);
		mProNameTxt.setText(EvaluationActivity.skuName);
		mProAttributeTxt.setText(EvaluationActivity.skuAttribute);
		mProPriceTxt.setText("￥"+EvaluationActivity.skuPrice);

		mGridView = (GridView) getView().findViewById(R.id.photoGrid);
		mSureBut = (Button) getView().findViewById(R.id.sunsingle_fragment_publish_but);
		
		if(EvaluationActivity.sunSingleStatus ){
			isSunSingleImg.setVisibility(View.VISIBLE);
			mLin.setVisibility(View.GONE);
			mButtomRelat.setVisibility(View.GONE);
		}else {
			isSunSingleImg.setVisibility(View.GONE);
			mLin.setVisibility(View.VISIBLE);
			mButtomRelat.setVisibility(View.VISIBLE);
		}
		
		
		Init();
	}

	private void Init() {

		mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(getActivity());
		adapter.update();
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.bmp.size()) {
				new PopupWindows(getActivity(), mGridView);
				} else {
					Intent intent = new Intent(getActivity(),
							PhotoPreviewActivity.class);
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

		mSureBut.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View paramView) {
				
				List<String> list = new ArrayList<String>();				
				for (int i = 0; i < Bimp.drr.size(); i++) {
					String Str = Bimp.drr.get(i).substring( 
							Bimp.drr.get(i).lastIndexOf("/") + 1,
							Bimp.drr.get(i).lastIndexOf("."));
					list.add(FileUtils.SDPATH+Str+".jpg");	

				}
				System.out.println(list);
				// 高清的压缩图片全部就在  list 路径里面了
				// 高清的压缩过的 bmp 对象  都在 Bimp.bmp里面

				final String ss = mEditText.getText().toString();
				if(ss == null || "".equals(ss)){
					App.showShortToast(R.string.please_enter_the_evaluation_of_the_content);
					return;
				}
				
				/** 评价字数不用做限定  */
//				if( ss.length() <10 || ss.length()>500){
//					App.showShortToast("评价字数不符合要求");
//					return;
//				}
				
				if( list.size() == 0 ){
					App.showShortToast(R.string.please_select_at_least_one_picture);
					return;
				}

				((BaseActivity) getActivity()).showLoadingDialog("");
				FinalHttp fh = new FinalHttp();
				AjaxParams params = new AjaxParams();
				params.put("orderItemId", EvaluationActivity.orderId+"");
				params.put("content", ss);
				fh.addHeader("X-Ticket", BaseActivity.getUUID(getActivity()));
				//动态添加图片
				for (int i = 0; i < list.size(); i++) {
						try {
							params.put("file"+i, new File(list.get(i).toString()));
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}	
				}
				
				fh.post(Constants.IP+"/rest/reviews/sunSingle", params, new AjaxCallBack<Object>() {
					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						App.showLog("t=="+t.toString());
						App.showShortToast(R.string.publishing_failure);
						((BaseActivity) getActivity()).dismissLoadingDialog();
					}

					@Override
					public void onSuccess(Object t) {
						super.onSuccess(t);
						App.showLog("t=="+t);
						((BaseActivity) getActivity()).dismissLoadingDialog();
						App.showShortToast(R.string.publishing_success);
						
						isSunSingleImg.setVisibility(View.VISIBLE);
						mLin.setVisibility(View.GONE);
						mButtomRelat.setVisibility(View.GONE);
						
						// 完成上传服务器后 .........
						/** 将bimp内保存的内容清空，删除文件夹，适配器刷新  */
						Bimp.bmp.clear();
						Bimp.drr.clear();
						Bimp.max = 0;
						FileUtils.deleteDir();
						adapter.notifyDataSetChanged();
					}
					
				});

			}
		});

	}
	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			return (Bimp.bmp.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			@SuppressWarnings("unused")
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grid,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.bmp.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.bmp.get(position));
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.drr.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							try {
								String path = Bimp.drr.get(Bimp.max);
								System.out.println("path=="+path);
								Bitmap bm = Bimp.revitionImageSize(path);
								Bimp.bmp.add(bm);
								String newStr = path.substring(
										path.lastIndexOf("/") + 1,
										path.lastIndexOf("."));
								FileUtils.saveBitmap(bm, "" + newStr);
								Bimp.max += 1;
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
							} catch (IOException e) {

								e.printStackTrace();
							}
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	@Override
	public void onResume() {
		super.onResume();
		adapter.update();
	}


	public class PopupWindows extends PopupWindow {

		@SuppressWarnings({ "deprecation" })
		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();
			//目的为了在阴影部分取消popwindow
			view.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
					dismiss();
					return false;
				}
			});

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),
							PhotoAlbumActivity.class);
					startActivity(intent);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	private String path = "";

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String state = Environment.getExternalStorageState();
		if (!state.equals(Environment.MEDIA_MOUNTED)) {
			App.showShortToast(R.string.no_sd_card);
			return;
		}

		File file = new File(Environment.getExternalStorageDirectory()
				+"/hqhs/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		App.showLog("path==="+path);
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, 1002);
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		App.showLog("requestCode=="+requestCode);
		App.showLog("resultCode=="+resultCode);
		App.showLog("data=="+data);
		switch (requestCode) {
		case 1002:
			if (Bimp.drr.size() < 9 && resultCode == -1) {
				Bimp.drr.add(path);
			}
			break;
		}
	}

	@Override
	public void onDestroy() {
		Bimp.bmp.clear();
		Bimp.drr.clear();
		Bimp.max = 0;
		FileUtils.deleteDir();
		super.onDestroy();
	}


}
